<template>
    <el-form
        :inline="true"
        ref="searchFormRef"
        style="max-width: 100%"
        label-width="auto"
        :model="queryConditions"
        class="demo-ruleForm"
        status-icon
    >
        <el-form-item label="客户" prop="customerId">
            <el-select
                v-model="queryConditions.customerId"
                style="width: 200px"
                size="large"
                placeholder="请选择"
                clearable
            >
                <el-option
                    v-for="customer in customerList"
                    :key="customer.id"
                    :label="customer.name"
                    :value="customer.id"
                />
            </el-select>
        </el-form-item>
        <el-form-item label="时间范围" prop="dateRange">
            <el-date-picker
                v-model="queryConditions.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="large"
            />
        </el-form-item>
        <el-button type="primary" :icon="Search" @click="search">查询</el-button>
        <el-button type="primary" :icon="RefreshRight" @click="resetForm">重置</el-button>
    </el-form>
    <SalesOrderExecutionStatusLimitPage
        :table-data="formattedTableData"
        :columns="tableColumns"
        :current-page="pageNo"
        :total="allPage"
        :page-size="pageSize"
        @page-change="handlePageChange"
        @action="handleTableAction"
    />
</template>

<script setup lang="ts">
import { onMounted } from 'vue';
import { Search, RefreshRight } from '@element-plus/icons-vue';
import { ref, computed, reactive, nextTick } from 'vue';
import { ElMessage, type FormInstance, ElLoading } from 'element-plus';
import SalesOrderExecutionStatusLimitPage from "@/salesOrderExecutionStatus/SalesOrderExecutionStatusLimitPage.vue";
import request from "@/util/request.ts";

let pageNo = ref(1);
let pageSize = ref(10);
let allPage = ref(0);
const searchFormRef = ref<FormInstance>();

// 查询条件
const queryConditions = reactive({
    customerId: null,
    dateRange: []
});

// 查询
const search = () => {
    pageNo.value = 1; // 重置到第一页
    fetchData(1);
};

// 重置表单
const resetForm = () => {
    if (!searchFormRef.value) return;
    nextTick(() => {
        searchFormRef.value!.resetFields();
        queryConditions.customerId = null;
        queryConditions.dateRange = [];
        pageNo.value = 1;
        fetchData(1);
    });
};

let tableData = ref<any[]>([]);

// 格式化表格数据
const formattedTableData = computed(() => {
    return tableData.value.map((item, index) => ({
        ...item,
        index: (pageNo.value - 1) * pageSize.value + index + 1,
        totalAmount: Number(item.totalAmount).toFixed(2),
        totalTaxValue: Number(item.totalTaxValue).toFixed(2),
        customerName: item.customerName || '未知客户', // 处理 null
        totalQuantity: item.totalQuantity ?? 0 // 处理 null
    }));
});

// 表格列配置
const tableColumns = ref([
    { prop: 'index', label: '序号', width: 80 },
    { prop: 'customerId', label: '客户ID', width: 120 },
    { prop: 'customerName', label: '客户名称', width: 200 },
    { prop: 'orderCount', label: '订单数量', width: 120 },
    { prop: 'totalAmount', label: '总金额', width: 150 },
    { prop: 'totalTaxValue', label: '总税额', width: 150 },
    { prop: 'totalQuantity', label: '总商品数量', width: 150 }
]);

// 分页处理
const handlePageChange = (newPage: number) => {
    pageNo.value = newPage;
    fetchData(newPage);
};

// 导出数据
const handleExport = async () => {
    const params = {
        pageNo: pageNo.value,
        pageSize: pageSize.value,
        customerId: queryConditions.customerId,
        startDate: queryConditions.dateRange[0] ? queryConditions.dateRange[0].toISOString() : null,
        endDate: queryConditions.dateRange[1] ? queryConditions.dateRange[1].toISOString() : null
    };
    const loading = ElLoading.service({ text: "正在导出..." });
    try {
        const response = await request.post(
            "/xs/SalesOrderSummary/exportSummaryByCustomer",
            params,
            { responseType: "blob" }
        );
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", "客户销售订单汇总.xlsx");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        ElMessage.success("导出成功");
    } catch (error) {
        console.error("导出失败:", error);
        ElMessage.error("导出失败，请稍后重试");
    } finally {
        loading.close();
    }
};

// 处理表格操作
const handleTableAction = (actionName: string) => {
    if (actionName === 'export') {
        handleExport();
    }
};

// 获取数据
async function fetchData(page: number) {
    try {
        const response = await request.post('/xs/SalesOrderSummary/selectSummaryByCustomer', {
            pageNo: page,
            pageSize: pageSize.value,
            customerId: queryConditions.customerId,
            startDate: queryConditions.dateRange[0] ? queryConditions.dateRange[0].toISOString() : null,
            endDate: queryConditions.dateRange[1] ? queryConditions.dateRange[1].toISOString() : null
        });
        tableData.value = response.data.data.list;
        allPage.value = response.data.data.total;
    } catch (error) {
        ElMessage.error('获取客户汇总数据失败');
        tableData.value = [];
        allPage.value = 0;
    }
}

// 获取客户列表
const customerList = ref<any[]>([]);
const fetchAllCustomers = async () => {
    try {
        const res = await request.post('/basic/Customer/selectAllCustomer');
        customerList.value = res.data.data;
    } catch (e) {
        ElMessage.error('获取客户数据失败');
        console.error('Error fetching customers:', e);
        customerList.value = [];
    }
};

onMounted(() => {
    fetchData(1);
    fetchAllCustomers();
});
</script>

<style scoped>
</style>
